
const db = require('../../../db/index')

const addAsync = (req, res) => {
    let { name, date, remark } = req.body.data
    if (!name || !date) return res.send({ status: 500, message: '用户名或密码不能为空' })
    if (!remark) remark = ''
    const sql = `insert into t_sad(name,date,remark) values(?,?,?)`
    db.query(sql, [name, date, remark], (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '添加失败' })
        res.send({ status: 200, message: '添加成功' })
    })
}


// 分页查询加模糊查询
const getAsync = (req, res) => {
    const data = req.body.data;
    var { name, date, pageSize, pageIndex } = data;
    if (!name) {
        name = ''
    }
    if (!date) {
        date = ''
    }
    let sql = `SELECT * FROM t_sad where name like '%${name}%' and date like '%${date}%' LIMIT ${(pageIndex - 1) * 10},${pageSize}`;

    db.query(sql, [name, date, pageSize, pageIndex], (err, result) => {
        if (err) {
            console.error(err);
            return handleDatabaseError(res, err);
        }

        if (result.length === 0) {
            return res.send({ status: 404, message: '未找到数据', data: [] });
            // return res.status(404).send({ status: 404, message: '未找到数据' });
        }

        res.status(200).send({ status: 200, message: '查询成功', data: result });
    });
};

// 错误处理函数
const handleDatabaseError = (res, err) => {
    console.error('数据库查询出错:', err);
    res.status(500).send({ status: 500, message: '服务器错误' });
};


const modifyAsync = (req, res) => {
    const sql = `update t_sad set ? where id=?`
    const data = req.body
    db.query(sql, [data.data, data.id], (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '修改失败' })
        res.send({ status: 200, message: '修改成功' })
    })
}

const deleteAsync = (req, res) => {
    const sql = 'delete from t_sad where id=?'
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.send({ status: 500, message: err.message })
        if (result.affectedRows !== 1) return res.send({ status: 500, message: '删除失败' })
        res.send({ status: 200, message: '删除成功' })
    })
}

module.exports = {
    addAsync: addAsync,
    getAsync: getAsync,
    deleteAsync: deleteAsync,
    modifyAsync: modifyAsync
}